import { observable, action, toJS } from 'mobx';
import { message } from 'antd';
import { WeaTools } from 'ecCom';
import Api from '../apis/menu';

const formatMenuData = datas => datas.map((d) => {
  const parentId = d.parentId || '0';
  const isportal = d.isportal || d.hpid;
  return {
    hpid: d.hpid || '',
    infoId: d.infoId || d.hpid,
    numId: isportal ? `portal_${d.hpid}` : d.infoId,
    id: `${parentId}-${d.infoId || d.id}`,
    parentId,
    levelid: `${parentId}-${!isportal
        ? d.levelid
        : d.levelid && d.pid === '0'
        ? `${d.levelid.split('_')[0] % 20}_portal`
        : d.levelid || '0'}`,
    icon: !d.icon
      || d.icon === '/images/homepage/baseelement_wev8.gif'
      || d.icon.indexOf('/images_face/') !== -1
      || d.icon.indexOf('/images/') !== -1
      || d.icon.indexOf('/image_secondary/') !== -1
      ? '' : d.icon,
    name: d.name || '',
    pinyin: d.pinyin || '',
    url: d.url && d.url.replace(/&#38;/g, '&'),
    routeurl: isportal && d.routeurl ? `/portal${d.routeurl.substring(1)}` : d.routeurl || '',
    mobxrouteurl: isportal && d.routeurl
      ? `/portal${d.routeurl.substring(1)}`
      : d.mobxrouteurl || '',
    fullrouteurl: d.fullrouteurl || '',
    target: d.target || 'mainFrame',
    child: d.child ? formatMenuData(d.child) : [],
    count: d.count !== undefined ? `${d.count}` : '',
    countId: d.countId || '',
    titleUrlIcon: d.titleUrlIcon || '',
    titleUrl: d.titleUrl || '',
    tagColor: d.tagColor || '',
    hasTopLine: d.hasTopLine || '',
  };
});

const { href } = window.location;

const initState = {
  hasMenu: href.indexOf('/spa/email/') > 0 || href.indexOf('/wui/') < 0,
  loading: false,
  datas: [],
  mode: localStorage.weaEmailSingleMenuMode || 'inline',
  selectedKey: '',
};

export default class EmailMenuStore {
  @observable hasMenu = initState.hasMenu;
  @observable loading = initState.loading;
  @observable datas = initState.datas;
  @observable mode = initState.mode;
  @observable selectedKey = initState.selectedKey;
  @observable isNotWeiSearch = true;

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
    return this;
  }

  @action
  clear = () => this.setState(initState)

  @action
  getMenu = async (params, isMenu = false) => {
    const themeInfo = WeaTools.ls.getJSONObj('theme-themeInfo');
    // 如果是默认布局下从微搜进入模块， 不进行左侧栏接口请求及刷新
    const rule = window.isDev ? true : (this.isNotWeiSearch || href.indexOf('/spa/email/') > 0 || (themeInfo && themeInfo.themeLayoutType != 1));
    if (rule) {
      this.loading = true;
      const res = await Api.getMenu(params);
      try {
        if (res) {
          this.datas = formatMenuData(res);
        } else {
          message.error(res.msg);
        }
      } catch (e) {
        message.error(e);
      }
      this.loading = false;
      if (!isMenu) {
        // 更新左侧菜单数据
        window.doThemeAction && window.doThemeAction('onLoadEmailMenu');
      }
      return res;
    }
  }

  @action
  setSelectedKey = (location) => {
    const { pathname, query } = location;
    if (pathname.indexOf('main/email/') >= 0) {
      toJS(this.datas).forEach((d) => {
        if (pathname === 'main/email/folder' && query.folderid !== undefined) {
          d.child && d.child.forEach((c) => {
            c.mobxrouteurl.indexOf(`folderid=${query.folderid}`) >= 0 && (this.selectedKey = c.id);
          });
        } else if (pathname === 'main/email/tag' && query.labelid !== undefined) {
          d.child && d.child.forEach((c) => {
            c.mobxrouteurl.indexOf(`labelid=${query.labelid}`) >= 0 && (this.selectedKey = c.id);
          });
        } else if (d.mobxrouteurl.indexOf(pathname.replace('main', '')) >= 0) {
          this.selectedKey = d.id;
        }
      });
    }
  }
}
